package org.jctc.els.modules.biz.service.message.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jctc.els.modules.biz.mapper.message.MessageMapper;
import org.jctc.els.modules.biz.mapper.message.MessageUserMapper;
import org.jctc.els.modules.biz.mapper.message.MessageWaitPullMapper;
import org.jctc.els.modules.biz.mapper.user.UserMapper;
import org.jctc.els.modules.biz.service.message.IMessageService;
import org.jctc.els.modules.biz.entity.message.Message;
import org.jctc.els.modules.biz.entity.message.MessageExpand;
import org.jctc.els.modules.biz.entity.message.MessageUser;
import org.jctc.els.modules.biz.entity.message.MessageWaitPull;
import org.jctc.els.modules.biz.entity.user.User;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author lyh
 * @since 2021-02-26
 */
@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MessageWaitPullMapper messageWaitPullMapper;

    @Autowired
    private MessageUserMapper messageUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(MessageExpand messageExpand) {
        boolean result = false;
		Long userId = AuthUtil.getUserId();
		messageExpand.setCreateTime(new Date());
		messageExpand.setModifiedTime(new Date());
		messageExpand.setCreateUserId(userId);
        String messageTypeCode = messageExpand.getMessageTypeCode();
        if (messageTypeCode.equals(2)){
        }
        result = messageMapper.insert(messageExpand) > 0;
        // 临时保存个人通知
        if (BooleanUtil.isTrue(result)){
            if (ObjectUtil.equals(messageExpand.getMessageTypeCode(), "1")) {
                result = saveMessageWaitPull(messageExpand);
            }
        }
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    private boolean saveMessageWaitPull(MessageExpand messageExpand) {
        boolean result = false;
        List<User> userList = messageExpand.getUserList();
        if (CollUtil.isNotEmpty(userList)) {
            List<MessageWaitPull> messageWaitPulls = new ArrayList<>();
            messageWaitPulls = userList.stream().map(user -> {
                MessageWaitPull messageWaitPull = new MessageWaitPull();
                messageWaitPull.setUserId(user.getId());
                messageWaitPull.setMessageId(messageExpand.getId());
                messageWaitPull.setCode(messageExpand.getMessageObjectCode());
                return messageWaitPull;
            }).collect(Collectors.toList());
            result = messageWaitPullMapper.insertList(messageWaitPulls) > 0;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(Long id) {
        boolean result = false;
        result = messageMapper.deleteById(id) > 0;
        if (BooleanUtil.isFalse(result)){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return result;
        }
		messageWaitPullMapper.removeByMessageId(id);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(MessageExpand message) {
        boolean result = false;
        // 临时保存个人通知
        if (ObjectUtil.equals(message.getMessageTypeCode(), "1")) {
            result = messageWaitPullMapper.removeByMessageId(message.getId()) > 0;
            if (BooleanUtil.isTrue(result)){
                result = saveMessageWaitPull(message);
                if (BooleanUtil.isFalse(result)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
            }
        }else{
            result =true;
        }
        if (BooleanUtil.isTrue(result)){
            result=messageMapper.updateById(message) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return result;
    }

    @Override
    public Page<MessageExpand> selectListByPage(Integer pageNum, Integer pageSize, String title, String messageTypeCode, Long schoolId) {
        Page<MessageExpand> messagePage = new Page<>(pageNum, pageSize);
        return messageMapper.selectListByPage(messagePage, title, messageTypeCode,schoolId);
    }

    @Override
    public MessageExpand selectById(Long id) {
        MessageExpand messageExpand = messageMapper.selectById(id);
        if (messageExpand.getMessageTypeCode().equals("1")){
           List<User> list=messageWaitPullMapper.selectUsersByMessageId(id);
            messageExpand.setUserList(list);
        }
        return messageExpand;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean releaseMessage(MessageExpand messageExpand) {
        Long id = messageExpand.getId();
		Long userId = AuthUtil.getUserId();
		messageExpand.setReleaseDate(new Date());
		messageExpand.setReleaseFlag(true);
        boolean result = false;
            if (ObjectUtil.isNotNull(id)) {
                // 发布消息,修改
				messageExpand.setModifiedTime(new Date());
                result = messageMapper.updateById(messageExpand) > 0;
            } else {
                // 发布消息,新增
				messageExpand.setCreateUserId(userId);
				messageExpand.setCreateTime(new Date());
				messageExpand.setModifiedTime(new Date());
                result = messageMapper.insert(messageExpand) > 0;
            }

        // 查询消息接收人
        List<MessageWaitPull> userList = getMessageUser(messageExpand);
        if (!messageExpand.getMessageTypeCode().equals("1")){
            if (CollUtil.isNotEmpty(userList)) {
                result = messageWaitPullMapper.insertList(userList) > 0;
                if (BooleanUtil.isTrue(result)){
                    for (MessageWaitPull messageWaitPull : userList) {
                        MessageUser messageUser = new MessageUser();
                        messageUser.setUserId(messageWaitPull.getUserId());
                        messageUser.setMessageId(messageExpand.getId());
                        messageUser.setCode(messageExpand.getMessageObjectCode());
                        messageUser.setReadFlag(1);
                        messageUser.setCreateTime(new Date());
                        result =  messageUserMapper.insert(messageUser)>0;
                    }
                }
            }
        }else{
            result=true;
        }
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    @Override
    public boolean allRead(Long userId) {
        boolean b = messageUserMapper.allRead(userId) > 0;
        return b ;
    }

    @Override
    public boolean deleteMessage(Long id, Long userId) {
        boolean b = messageUserMapper.deleteMessage(id, userId) > 0;
        return b;
    }

    @Override
    public Page<MessageExpand> selectMessageByUserId(Integer pageNum, Integer pageSize, String title, String messageTypeCode, Long userId) {
        Page<MessageExpand> messagePage = new Page<>(pageNum, pageSize);
        Page<MessageExpand> messageExpandPage = messageMapper.selectMessageByUserId(messagePage, title, messageTypeCode, userId);
        return messageExpandPage;
    }

    private List<MessageWaitPull> getMessageUser(MessageExpand messageExpand) {
        List<MessageWaitPull> userList = new ArrayList<>();
        String messageObjectCode = messageExpand.getMessageObjectCode();
        String messageTypeCode = messageExpand.getMessageTypeCode();
        Long messageId = messageExpand.getId();
        switch (messageTypeCode) {

        }
        return userList;
    }

    @Override
    public Boolean saveMessage(Message message){
        Boolean b = messageMapper.insert(message)>0;
        return b;
    }
}
